
<!DOCTYPE html>
<html>
<head>
<title>E Shop Cart Widget A Flat Responsive Widget Template</title>

	<!-- 预加载字体文件，提高页面加载性能 -->
	<link rel="preload" href="/cart/fonts/FjallaOne-Regular.ttf" as="font" type="font/ttf" crossorigin>
	<link rel="preload" href="/cart/fonts/OpenSans-Regular.ttf" as="font" type="font/ttf" crossorigin>
	<!-- 移动设备适配设置 -->
	<meta name="viewport" content="width=device-width, initial-scale=1" />
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="keywords" content="E Shop Cart Widget Responsive, Login Form Web Template, Flat Pricing Tables, Flat Drop-Downs, Sign-Up Web Templates, Flat Web Templates, Login Sign-up Responsive Web Template, Smartphone Compatible Web Template, Android Compatible Web Template, Free Web Designs for Nokia, Samsung, LG, Sony Ericsson, Motorola Web Design" />
	<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>

	<!-- 引入自定义样式表 -->
	<link rel="stylesheet" href="/cart/css/style.css" type="text/css" media="all" />

	<!-- 引入jQuery库和删除商品的JavaScript功能 -->
	<script type="text/javascript" src="/cart/js/jquery-1.11.1.min.js"></script>
	<!-- 删除第一个商品的动画效果 模板自带-->
	<script>$(document).ready(function(c) {
		$('.alert-close1').on('click', function(c){
			$('.close1').fadeOut('slow', function(c){
		  		$('.close1').remove();
			});
		});	  
	});
	</script>
	<!-- 删除第二个商品的动画效果 -->
	<script>$(document).ready(function(c) {
		$('.alert-close2').on('click', function(c){
			$('.close2').fadeOut('slow', function(c){
		  		$('.close2').remove();
			});
		});	  
	});
	</script>
	<!-- 删除第三个商品的动画效果 -->
	<script>$(document).ready(function(c) {
		$('.alert-close3').on('click', function(c){
			$('.close3').fadeOut('slow', function(c){
		  		$('.close3').remove();
			});
		});	  
	});
	</script>


</head>

<!-- Body-Starts-Here -->
<body>

	<h1>E SHOP CART WIDGET</h1>

	<!-- Content-Starts-Here -->
	<div class="container">

		<!-- Mainbar-Starts-Here -->
		<div class="main-bar">
			<div class="product" style="width: 60%">
				<h3>Product</h3>
			</div>
			<div class="quantity" style="width: 12%">
				<h3>Quantity</h3>
			</div>
			<div class="price" style="width: 12%">
				<h3>Price</h3>
			</div>
			<div class="price" style="width: 12%">
				<h3>操作</h3>
			</div>
			<div class="clear"></div>
		</div>
		<!-- //Mainbar-Ends-Here -->

		<!-- Items-Starts-Here -->
		<div class="items">


		</div>
		<!-- //Items-Ends-Here -->

		<!-- Total-Price-Starts-Here -->
		<div class="total">
			<div class="total1">Total Price</div>
			<div class="total2"></div>
			<div class="clear"></div>
		</div>
		<!-- //Total-Price-Ends-Here -->

		<!-- Checkout-Starts-Here -->
		<div class="checkout">
			<div class="discount">
				<span>Apply Discount Code</span> <input type="text">
			</div>
			<div class="add">
				<a href="shop">Go To Shop</a>
			</div>
			<div class="checkout-btn" id="settlementBtn">
				<a href="checkout">Checkout</a>
			</div>
			<div class="clear"></div>
		</div>
		<!-- //Checkout-Ends-Here -->

	</div>


	<script>

		function deleteItem(productId, userId) {
			if (confirm('确定要删除这个商品吗？')) {
				$.ajax({
					url: '/cart/delete',
					method: 'POST',
					data: {
						productid: productId,
					},
					success: function(response) {
						/*if (response.code === 200) {*/
							alert('商品已成功删除');
							loadCartItems();
						/*} else {
							alert('删除失败：' + (response.message || '请稍后重试'));
							loadCartItems();
						}*/
					},
					error: function(xhr, status, error) {
						let errorMsg = '删除失败：';

						if (xhr.status === 401) {
							errorMsg += '请先登录';
							setTimeout(() => {
								window.location.href = '/login';
							}, 1500);
						} else if (xhr.status === 404) {
							errorMsg += '商品不存在或已被删除';
						} else {
							errorMsg += '网络错误，请稍后重试';
						}
						alert(errorMsg);
					}
				});
			}
		}


			// 页面加载完成后立即加载购物车
			loadCartItems();

		function loadCartItems() {
			// 显示加载中提示
			$('.items').html('<p style="text-align: center; padding: 20px;">加载中...</p>');

			$.ajax({
				url: '/cart/list',
				method: 'GET',
				dataType: 'json',
				timeout: 10000, // 设置超时时间为10秒
				success: function (response) {
					if (response && response.data) {
						let cartHtml = '';
						let totalPrice = 0;

						// 检查数据是否为空数组
						if (response.data.length === 0) {
							$('.items').html('<p style="text-align: center; padding: 20px;">购物车是空的</p>');
							$('.total2').text('$ 0.00');
							return;
						}

						// 处理数据
						// 修改商品项模板
						response.data.forEach(function (item, index) {
							if (item && item.product) {
								cartHtml += `
        <div class="item${index + 1}" style="margin: 15px 0; padding: 10px; border-bottom: 1px solid #eee; min-height: 140px;">
            <div style="display: flex; align-items: center; gap: 20px; position: relative;">
                <select class="item-checkbox" data-productid="${item.productid}" data-userid="${item.userid}"
                       style="margin-left: 10px;" onchange="updateCheckedStatus(this, ${item.productid}, ${item.userid})">
                    <option value="0" ${item.ischecked === 0 ? 'selected' : ''}>不选择</option>
                    <option value="1" ${item.ischecked === 1 || item.ischecked === undefined ? 'selected' : ''}>选择</option>
                </select>
                <div class="image${index + 1}" style="flex: 0 0 120px; height: 120px; margin-left: 15px;">
                    <img src="../${item.product.imgurl}"
                        alt="item${index + 1}"
                        style="width: 100%; height: 100%; object-fit: cover; border: 1px solid #eee;">
                </div>
                <div class="title${index + 1}" style="flex: 1; min-width: 100px;">
                    <p style="margin: 0; font-size: 16px; line-height: 1.4;">${item.product.name || '未知商品'}</p>
                </div>
                <div class="quantity${index + 1}" style="flex: 0 0 100px; text-align: center;">
                    <input type="number" name="quantity" min="1" max="100" value="${item.count || 1}"
                           onchange="updateQuantity(${item.productid}, ${item.userid}, this.value, ${item.product.price})"
                           oninput="this.value = this.value > 100 ? 100 : (this.value < 1 ? 1 : this.value)"
                           style="width: 60px; padding: 5px; text-align: center; border: 1px solid #ddd;">
                </div>
                <div class="price${index + 1}" style="flex: 0 0 100px; text-align: right;">
                    <p id="price_${item.productid}" style="margin: 0; font-size: 16px; font-weight: bold;">
                        $ ${((item.product.price || 0) * item.count).toFixed(2)}
                    </p>
                </div>
                <div class="operation" style="flex: 0 0 80px; text-align: center;">
                    <button onclick="deleteItem(${item.productid}, ${item.userid})"
                            style="padding: 5px 10px; background-color: #ff4444; color: white; border: none; border-radius: 4px; cursor: pointer;">
                        删除
                    </button>
                </div>
            </div>
        </div>`;
							}
						});

						$('.items').html(cartHtml || '<p style="text-align: center; padding: 20px;">购物车是空的</p>');
						updateTotalPrice();
					} else {
						throw new Error('无效的响应数据');
					}
				},
				error: function (xhr, status, error) {
					console.error('购物车加载失败:', status, error);
					let errorMessage = '加载失败，请刷新页面重试';

					if (xhr.status === 401) {
						window.location.href = '/login';
						return;
					} else if (xhr.status === 404) {
						errorMessage = '服务未找到，请稍后重试';
					} else if (status === 'timeout') {
						errorMessage = '加载超时，请检查网络后重试';
					}

					$('.items').html(`
                    <p style="text-align: center; padding: 20px;">
                        ${errorMessage}
                        <br>
                        <button onclick="location.reload()" style="margin-top: 10px; padding: 5px 10px;">刷新页面</button>
                    </p>
                `);
					$('.total2').text('$ 0.00');
				}
			});
		}

		// 更新商品选中状态
		function updateCheckedStatus(selectElement, productId, userId) {
			const isChecked = parseInt(selectElement.value);
			// 获取当前商品的数量，避免后端将count设为0
			const currentQuantity = parseInt($(selectElement).closest('div').find('input[type="number"]').val());

			$.ajax({
				url: '/cart/edit',
				method: 'POST',
				data: {
					productid: productId,
					userid: userId,
					ischecked: isChecked,
					count: currentQuantity // 添加当前数量，防止后端将count设为0
				},
				success: function(response) {
					// 更新成功后重新计算总价
					updateTotalPrice();
				},
				error: function(xhr, status, error) {
					alert('更新选中状态失败，请重试');
					loadCartItems(); // 重新加载购物车
				}
			});
		}


		// 修改更新总价的函数
		function updateTotalPrice() {
			let total = 0;
			$('.items > div').each(function() {
				const select = $(this).find('.item-checkbox');
				if (select.val() === '1') {
					const quantity = parseInt($(this).find('input[type="number"]').val());
					const price = parseFloat($(this).find('[id^="price_"]').text().replace('$ ', ''));
					if (!isNaN(quantity) && !isNaN(price)) {
						const itemTotal = (price / quantity) * quantity;
						total += itemTotal;
					}
				}
			});
			$('.total2').text(`$ ${total.toFixed(2)}`);
		}

		// 添加下拉框变化事件监听
		$(document).on('change', '.item-checkbox', function() {
			updateTotalPrice();
		});


		function updateQuantity(productId, userId, newQuantity, price) {
			$.ajax({
				url: '/cart/edit',
				method: 'POST',
				data: {
					productid: productId,
					userid: userId,
					count: newQuantity
				},
				success: function(response) {

						// 更新单个商品总价
						const itemTotal = price * newQuantity;
						$(`#price_${productId}`).text(`$ ${itemTotal.toFixed(2)}`);

						// 重新计算总价
						updateTotalPrice();

				},
				error: function(xhr, status, error) {
					alert('更新数量失败，请重试');
					location.reload();
				}
			});
		}




		$("#settlementBtn").click(function(e){
			// 阻止默认的链接跳转行为
			e.preventDefault();
			// 准备数据
			let productids = "";
			let counts = "";
			let hasSelectedItems = false;
			let orderItems = [];
			let userId = null;
			let totalAmount=0;

			// 遍历所有商品项，找出被选中的商品
			$('.items > div').each(function() {
				const select = $(this).find('.item-checkbox');
				if (select.val() === '1') {
					hasSelectedItems = true;
					// 获取商品ID和数量
					let productId = select.data('productid');
					userId = select.data('userid');
					let count = parseInt($(this).find('input[type="number"]').val());

					let productName = $(this).find('[class^="title"]').text().trim();
					let productPrice = parseFloat($(this).find('[id^="price_"]').text().replace('$ ', '')) / count;
					let productImg = $(this).find('img').attr('src').replace('../', '');

					// 添加到字符串中，用逗号分隔
					productids += (productId + ",");
					counts += (count + ",");

					//计算商品总价被累加到订单总金额
					let itemTotal=productPrice*count;
					totalAmount+=itemTotal;

					// 添加到订单项数组
					orderItems.push({
						productid: productId,
						count: count,
						productname: productName,
						price: productPrice,
						imgurl: productImg
					});
				}
			});

			// 检查是否有选中的商品
			if (!hasSelectedItems) {
				alert("请至少选择一件商品进行结算");
				return;
			}

			productids = productids.substring(0, productids.length-1);
			counts = counts.substring(0, counts.length-1);

			// 将整个订单创建过程改为单个请求，由后端处理事务
			$.ajax({
				url: '/order/createWithItems',
				method: 'POST',
				contentType: 'application/json',
				data: JSON.stringify({
					money: totalAmount.toFixed(2),
					items: orderItems
				}),
				success: function(response) {
					console.log("服务器返回的完整响应:", response); // 添加调试日志
					if (response && response.code === 200) {
						const orderId = response.data;
						console.log("获取到的订单ID:", orderId); // 添加调试日志

						// 创建成功后直接跳转到结算页面
						location.href = "checkout?productids=" + productids + "&counts=" + counts + "&orderid=" + orderId;
					} else {
						alert("创建订单失败：" + (response.msg || "未知错误"));
					}
				},
			});


		});



	</script>
</body>
</html>